// pages/addbankcard/addbankcard.js
import { Sms } from '../../utils/sms.js'
var sms = new Sms();
Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		sendBtn: '发送验证码',
		sendBtnDisable: false,
		smsCodeIsSend: false,
		smsCodePass: false,
		smsCode: '',
		smsName: '',
		smsbankCard: '',
		smsIdCard: '',
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function (options) {
		sms.getAgentphone((data) => {
			if (data.msg) {
				this.setData({
					phone: data.phone,
				})
			}
		});
	},

	smsCode: function (event) {
		var smsCode = event.detail.value;
		this.setData({ smsCode: smsCode });
		if (smsCode.length >= 4) {
			sms.smsCodeCheck(smsCode, (data) => {
				if (data.msg) {
					this.setData({ smsCodePass: true });
				} else {
					this.setData({ smsCodePass: false });
					sms.showToast(data.err_msg)
				}
				this.setData({ smsCodeIsSend: true });
			});
		} else {
			this.setData({ smsCodePass: false });
		}
	},

	smsName: function (event) {
		var smsName = event.detail.value;
		this.setData({ smsName: smsName });
	},

	smsBankCard: function (event) {
		var smsBankCard = event.detail.value;
		this.setData({ smsBankCard: smsBankCard });
	},

	smsIdCard: function (event) {
		var smsIdCard = event.detail.value;
		this.setData({ smsIdCard: smsIdCard });
	},

	smsCheckAdd() {
		if (this.data.smsName == '' || this.data.smsBankCard == '' || this.data.smsIdCard=='') {
			sms.showToast('请完善信息后提交');
			return;
		}
		this.setData({ sendBtnLoading:true})
		sms.checkBankAndAdd(this.data.smsName, this.data.smsBankCard, this.data.smsIdCard, (data) => {
			this.setData({ sendBtnLoading: false })
			if (data.msg) {
				wx.showModal({
					title: '提示',
					content: '验证成功，点击确定前往银行卡管理',
					success: function (res) {
						wx.redirectTo({
							url: '../bankcard/bankcard',
						})
					}
				})
			}else{
				sms.showToast(data.err_msg);
			}
		})
	},

	sendSmsCode: function () {
		this.setData({
			smsIsSend: true,
			sendBtn: ''
		})
		var that = this;
		sms.sendSmsCode((data) => {
			that.setData({
				sendBtn: 60 + ' s',
				sendBtnDisable: true,
			})
			if (data.msg) {
				var time = 60
				that.setData({
					sendBtn: time + ' s'
				})
				that.se(time)
			} else {
				sms.showToast(data.err_msg)
			}
			this.setData({
				smsIsSend: false,
			})
		});
	},

	se: function (time) {
		time = time - 1;
		if (time <= 0) {
			this.setData({
				sendBtn: '发送验证码',
				sendBtnDisable: false,
			})
			return;
		}
		//省去倒计时函数
		var that = this;
		setTimeout(function () {
			that.setData({
				sendBtn: time + ' s'
			})
			that.se(time--);
		}, 1000)
	}

})